<template>
	<div>
		<el-dialog title="编辑用户信息" :visible.sync="udpateShow" :before-close="handleClose">
			<el-form ref="editForm" :model="userForm" :rules="rules" label-width="135px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="用户名" prop="userName">
							<el-input v-model="userForm.userName" disabled="disabled"></el-input>
						</el-form-item>
					</el-col>
					
					<el-col :span="12">
						<el-form-item label="是否超级管理员" prop="isRoot">
							<el-radio-group v-model="userForm.isRoot" size="medium">
								<el-radio border :label="1">是</el-radio>
								<el-radio border :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="登录密码" prop="password">
							<el-input type="password" v-model="userForm.password" placeholder="请输入登录密码" autocomplete="off" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="所属部门" prop="departmentName">
							<el-select v-model="userForm.departmentName" placeholder="请选择部门" @change="selectDepartmentCharge" style="width: 100%;">
								<el-option v-for=" (item,key) of departments" :key="key" :value="`${item.id}|${item.departmentName}`" :label="item.departmentName"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					
					<el-col :span="12" v-if="userForm.departmentId">
						<el-form-item label="所属店铺" prop="shopId">
							<!-- <el-select v-model="userForm.shopId" placeholder="请选择所属店铺">
								<el-option :label="item.shopName" :value="item.id" v-for="item of shopData" :key="item.id"></el-option>
							</el-select> -->
							<el-input v-model="shopName" placeholder="点击按钮选择店铺" readonly>
								<el-button size="mini" slot="suffix" @click="openShopDialog">选择店铺</el-button>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="真实姓名" prop="realName">
							<el-input v-model="userForm.realName" placeholder="请输入真实姓名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="昵称" prop="nickName">
							<el-input v-model="userForm.nickName" placeholder="请输入昵称" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="手机号" prop="phone">
							<el-input v-model="userForm.phone" placeholder="请输入手机号" autocomplete="off" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="邮箱地址" prop="email">
							<el-input v-model="userForm.email" placeholder="请输入邮箱地址" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			
			<div slot="footer">
				<el-button type="primary" @click="onSubmit('editForm')">提 交</el-button>
				<el-button @click="uChange">取 消</el-button>
			</div>
		</el-dialog>
		
		<el-dialog title="选择店铺" :visible.sync="showChooseShop" :before-close="closeShopDialog">
			<div>
				<el-form :inline="true" :model="searchForm">
					<el-form-item label="店铺名字">
						<el-input size="small" v-model="searchForm.keywords" placeholder="请输入店铺名字关键字" clearable style="width: 300px;"></el-input>
					</el-form-item>
					
					<el-form-item>
						<el-button type="primary" size="small" @click="searchShop">搜索</el-button>
						<el-button size="small" @click="resetSearch">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
			
			<el-table stripe border :data="shopData" style="width: 100%">
				<el-table-column type="index" fixed label="序号" width="50" align="center"></el-table-column>
				
				<el-table-column label="店铺logo" width="90" align="center">
					<template slot-scope="scope">
						<el-image fit="cover" style="width: 60px; height: 60px" :src="scope.row.shopLogo" :preview-src-list="[scope.row.shopLogo]"></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="shopName" label="店铺名称"></el-table-column>
				<el-table-column prop="phone" label="联系电话" width="140"></el-table-column>
				<el-table-column prop="shopAddress" label="店铺地址" width="300"></el-table-column>
				
				<el-table-column label="操作" width="120" align="center">
					<template slot-scope="scope">
						<el-button type="warning" size="small" v-if="scope.row.id == userForm.shopId">已选</el-button>
						<el-button type="primary" plain size="small" @click="chooseShop(scope.$index)" v-else>选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<div class="page">
				<el-pagination
					background
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:total="total"
					:page-size="pageSize"
					layout="total, prev, pager, next"
				></el-pagination>
			</div>
			
			<div slot="footer">
				<el-button type="primary" @click="closeShopDialog">关 闭</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import { UpdateUser, GetUser } from '@api/user/user'
	import { AllDepartmentList } from '@api/department/department'
	import { getShopList } from '@api/shop/shop'
	import md5 from 'js-md5'
	export default {
		props: ["uShow", "uId"],
		data() {
			var validatePassword = (rule, value, callback) => {
				if (this.userForm.password != null && this.userForm.password != '') {
					if (value === '') {
						callback(new Error('请输入密码'));
					} else {
						callback();
					}
				} else {
					callback();
				}
			};
			var validateMobile = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入手机号!'));
				} else if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) && !(/^0\d{2,5}-\d{7,8}$/.test(value))) {
					callback(new Error('请输入正确的手机号!'));
				} else {
					callback();
				}
			};
			return {
				udpateShow: this.uShow,
				updateId: this.uId,
				userForm: {
					userName: '',
					password: '',
					isRoot: '0',
					realName: '',
					nickName: '',
					phone: '',
					email: '',
					departmentId: '',
					departmentName: '',
					shopId: ''
				},
				rules: {
					password: [{ validator: validatePassword, trigger: 'blur' }],
					realName: [
						{ required: true, message: '请输入姓名', trigger: 'blur' },
						{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
					],
					email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
					phone: [{ required: true, validator: validateMobile, trigger: 'blur' }],
					departmentName: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
					departmentId: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
					shopId: [{ required: true, message: '请选择所属店铺', trigger: 'blur' }],
				},
				
				departments: [],
				parentIds: [],
				
				shopData: [],
				currentPage: 1,
				pageSize: 10,
				total: 0,
				
				shopName: '',
				showChooseShop: false,
				searchForm: {
					keywords: '',
				},
				
				loading: false
			}
		},
		watch: {
			uShow(val) {
				this.udpateShow = val; //②监听外部对props属性uShow的变更，并同步到组件内的data属性udpateShow中
				if(val) {
					this.loadUser(this.uId);
				}
			},
			udpateShow(val) {
				this.$emit("on-uShow-change", val); //③组件内对udpateShow变更后向外部发送事件通知
			},
			uId(val) {
				this.updateId = val; //②监听外部对props属性uShow的变更，并同步到组件内的data属性udpateShow中
			},
			updateId(val) {
				this.$emit("on-id-change", val); //③组件内对udpateShow变更后向外部发送事件通知
			}
		},
		methods: {
			getDepartment() { //获取部门信息
				AllDepartmentList()
					.then(res => {
						this.departments = res.data
						this.loading = false
					})
					.catch(() => {
						this.loading = false
					})
			},
			getShops() { //获取店铺列表
				getShopList({
					departmentId: parseInt(this.userForm.departmentId),
					shopName: this.searchForm.keywords,
					pageNum: this.currentPage,
					pageSize: this.pageSize
				})
					.then(res => {
						this.shopData = res.data.content;
						this.total = res.data.total;
						this.shopData.forEach(item => {
							if(item.id == this.userForm.shopId) {
								this.shopName = item.shopName;
							}
						})
					})
			},
			handleSizeChange(val) { //处理显示条数
				this.pageSize = val;
				this.getData();
			},
			handleCurrentChange(val) { //处理翻页
				this.currentPage = val;
				this.getData();
			},
			
			openShopDialog() {
				this.showChooseShop = true;
				this.resetSearch();
			},
			closeShopDialog() {
				this.showChooseShop = false;
			},
			chooseShop(index) {
				this.shopData.forEach((item, idx) => {
					if(idx == index) {
						this.userForm.shopId = item.id;
						this.shopName = item.shopName;
					}
				});
				this.$message.success('选择成功');
				// this.$refs['userForm'].clearValidate('shopId');
				
				setTimeout(() => {
					this.closeShopDialog();
				}, 500)
			},
			searchShop() {
				this.currentPage = 1;
				this.getShops();
			},
			resetSearch() {
				this.searchForm.keywords = '';
				this.currentPage = 1;
				this.getShops();
			},
			
			uChange() {
				this.udpateShow = !this.udpateShow;
				this.userForm.password = '';
				this.shopName = '';
			},

			onSubmit(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.loading = true;
						if (this.userForm.password != null && this.userForm.password != '') {
							let password = md5(this.userForm.password);
							this.userForm.password = password;
						}
						UpdateUser(this.userForm)
							.then(res => {
								this.$message.success('更新成功');
								this.$emit("on-loadlist-change"); //③组件内对myResult变更后向外部发送事件通知
								this.loading = false;
								this.uChange();
							})
							.catch(() => {
								// if (this.userForm.password != null && this.userForm.password != '') {
								// 	this.userForm.password = "";
								// }
								this.loading = false;
							})
					}
				})
			},
			handleClose(done) {
				this.$confirm('确定关闭吗').then(() => {
					// function(done)，done 用于关闭 Dialog
					this.shopName = '';
					done();
				}).catch(() => {
					// console.log("点击确定时触发");
				});
			},
			
			loadUser(id) {
				this.loading = true
				GetUser({
					userId: id + ""
				})
					.then(res => {
						this.userForm = res.data;
						this.userForm.password = null;
						this.loading = false;
						
						this.getShops();
					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			selectDepartmentCharge() {
				if (this.userForm.departmentName) {
					const [value, lable] = this.userForm.departmentName.split('|');
					this.userForm.departmentId = value;
					this.userForm.departmentName = lable;
					
					this.currentPage = 1;
					this.getShops();
				}
			}
		},
		mounted() {
			//预加载部门信息
			this.getDepartment();
		},
	}
</script>

<style lang="scss" scoped>
	form > div {
		width: auto;
	}
	
	.page {
		margin-top: 20px;
	}
</style>